package com.ddtech.business.task.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddtech.business.course.entity.Course;
import com.ddtech.business.course.service.CourseService;
import com.ddtech.business.task.entity.TaskCourse;
import com.ddtech.business.task.mapper.TaskCourseMapper;
import com.ddtech.business.task.service.TaskCourseService;
import com.ddtech.business.task.vo.req.TaskCourseReqVo;
import com.ddtech.business.task.vo.req.TaskReqVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 任务课程关联表 服务实现类
 * </p>
 *
 * @author bin_pu
 * @since 2023-02-06
 */
@Service
public class TaskCourseServiceImpl extends ServiceImpl<TaskCourseMapper, TaskCourse> implements TaskCourseService {
    @Autowired
    private CourseService courseService;
    @Resource
    private TaskCourseMapper taskCourseMapper;

    @Override
    public void saveTaskCourse(TaskReqVo taskReqVo) {
        if (CollUtil.isNotEmpty(taskReqVo.getTaskCourse())) {
            String taskId = taskReqVo.getId();
            QueryWrapper<TaskCourse> validQueryWrapper = new QueryWrapper();
            validQueryWrapper.eq("TASK_ID", taskId);
            this.remove(validQueryWrapper);
            List<TaskCourseReqVo> taskCourse = taskReqVo.getTaskCourse();
            taskCourse.forEach(item -> {
                TaskCourse taskCourseInfo = new TaskCourse();
                taskCourseInfo.setTaskId(taskId);
                taskCourseInfo.setCourseId(item.getCourseId());
                taskCourseMapper.insert(taskCourseInfo);
            });
        }
    }

    @Override
    public List<TaskCourseReqVo> getCourse(String taskId) {
        QueryWrapper<TaskCourse> validQueryWrapper = new QueryWrapper();
        validQueryWrapper.eq("TASK_ID", taskId);
        List<TaskCourse> list = this.list(validQueryWrapper);
        List<TaskCourseReqVo> reqVoList = list.stream().map(item -> {
            TaskCourseReqVo taskCourseReqVo = new TaskCourseReqVo();
            BeanUtil.copyProperties(item, taskCourseReqVo);
            String courseId = item.getCourseId();
            Course course = courseService.getById(courseId);
            if(course!=null){
                taskCourseReqVo.setCourseName(course.getCourseName());
            }
            return taskCourseReqVo;
        }).collect(Collectors.toList());
        return reqVoList;
    }
}
